package com.bbx.taxi.client.Activity.Order;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.OnClick;

import com.bbx.androidapi.util.SharedPreUtil;
import com.bbx.androidapi.util.ToastUtil;
import com.bbx.api.sdk.model.passanger.CancelOrder;
import com.bbx.api.sdk.model.passanger.Return.CancelReasonList;
import com.bbx.api.sdk.model.passanger.Return.WeightOrVolumn;
import com.bbx.api.sdk.model.passanger.Return.CancelReasonList.CancelReason;
import com.bbx.api.sdk.model.passanger.Return.Coupon.Coupons;
import com.bbx.api.sdk.model.passanger.Return.MyOrderList.MyOrderList;
import com.bbx.api.sdk.net.base.JsonBuild;
import com.bbx.api.sdk.net.passeger.conn.CancelOrderNet;
import com.bbx.api.sdk.net.passeger.conn.CodeNet;
import com.bbx.taxi.client.Task.BaseAsyncTask;
import com.bbx.api.util.SharedPreEncryptUtil;
import com.bbx.taxi.client.MyApplication;
import com.bbx.taxi.client.R;
import com.bbx.taxi.client.Activity.Base.BaseBBXActivity;
import com.bbx.taxi.client.Activity.Order.CancelOrderActivity.MyAdapter.ViewHolder_Cancel;
import com.bbx.taxi.client.Bean.Value;
import com.bbx.taxi.client.Bean.Extra.OrderMsg;
import com.bbx.taxi.client.Bean.Message.ObserverListener.DATA_STATUS;
import com.bbx.taxi.client.Bean.Message.ObserverListener.DATA_TYPE;
import com.bbx.taxi.client.DB.MyOrder.MyOrderDB;
import com.bbx.taxi.client.DB.MyOrder.MyOrderingDB;
import com.bbx.taxi.client.DB.MyOrder.OrderCencelDB;
import com.bbx.taxi.client.Task.CancelReasonListTask;
import com.bbx.taxi.client.Util.IsDataFail;
import com.bbx.taxi.client.Util.RequestUtils;
import com.bbx.taxi.client.emoji.MyConvertToMsg;
import com.bbx.taxi.client.widget.MaxByteLengthEditText;

public class CancelOrderActivity extends BaseBBXActivity implements OnItemClickListener{
	@Bind(R.id.listview)ListView listview;
	@Bind(R.id.btn_confirm)Button btn_confirm;
	@Bind(R.id.btn_cancel)Button btn_cancel;
	@Bind(R.id.et_message)MaxByteLengthEditText et_message;
	private String order_id;
	private CancelOrderTask mCancelOrderTask;
	private MyOrderingDB db_myordering;// 我的进行中的订单数据库
	private MyOrderDB db_myorder;// 我的全部的订单数据库
	private OrderCencelDB db_cencel;//取消订单数据库
	private String message="";
	private MyAdapter mMyAdapter;
	private List<CancelReason> list;
	public int reason_id=0;
	public int id=0;
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_cancle_order);
		super.onCreate(savedInstanceState);
		
	}
	@Override
	protected void initView() {
		setTitle(R.string.title_cancle_order);
		db_myordering = new MyOrderingDB();
		db_myorder= new MyOrderDB();
		db_cencel=new OrderCencelDB();
		list=new ArrayList<CancelReason>();
		btn_confirm.setOnClickListener(this);
		et_message.setMaxByteLength(60);
		et_message.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
			}
			
			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
			}
			
			@Override
			public void afterTextChanged(Editable arg0) {
				if(arg0.length()>0){
					btn_confirm.setEnabled(true);
				}else{
					boolean enanled=false;
					for (int i = 0; i < list.size(); i++) {
						if(mMyAdapter.isSelected.get(i)){
							enanled=true;
							return ;
						}
					}
					btn_confirm.setEnabled(enanled);
				}
				
			}
		});
		setCancelReason();
		mMyAdapter=new MyAdapter(context, list);
		mMyAdapter.isSelected.put(0, true);
		listview.setAdapter(mMyAdapter);
		listview.setOnItemClickListener(this);
		RequestUtils.requestCancelReasonList(context);
	
	}

	@Override
	protected void initData() {
		Intent intent=getIntent();
		order_id=intent.getExtras().getString(OrderMsg.cancel_order_id);
		
	}
	/**
	 * 设置本地的取消原因
	 */
	public void setCancelReason(){
		CancelReason mCancelReason=new CancelReasonList().new CancelReason();
		mCancelReason.setId(1);
		mCancelReason.setReason(this.getResources().getString(R.string.cancel_reason1));
		list.add(mCancelReason);
		 mCancelReason=new CancelReasonList().new CancelReason();
		mCancelReason.setId(2);
		mCancelReason.setReason(this.getResources().getString(R.string.cancel_reason2));
		list.add(mCancelReason);
		 mCancelReason=new CancelReasonList().new CancelReason();
		mCancelReason.setId(3);
		mCancelReason.setReason(this.getResources().getString(R.string.cancel_reason3));
		list.add(mCancelReason);
		if(list!=null&&list.size()>0){
		     message=list.get(0).getReason();
		}
	}
	@Override
	@OnClick({R.id.btn_cancel,R.id.btn_confirm})
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.btn_cancel:
			finish();
				break;
		case R.id.btn_confirm:
			MyOrderList mMyOrderList=db_myorder.onReadDB(order_id);
			if(mMyOrderList.getOrder_status()>=Value.ORDER_STATUS_ONCAR){
				ToastUtil.showToast(mApplication, R.string.order_status_no_cancel);
				return;
			}
			onCancelOrder();
			break;
		default:
			super.onClick(v);
			break;
		}
		
	}
	/**
	 * 取消订单
	 */
	public void onCancelOrder(){
		CancelOrder mCancelOrder = new CancelOrder(context);
		mCancelOrder.uid=mApplication.getUid();
		mCancelOrder.access_token=mApplication.getToken();
		mCancelOrder.order_id=order_id;
		mCancelOrder.reason=list.get(id).getReason()+";"+new MyConvertToMsg().parseEmoji(context,et_message.getText().toString());
		mCancelOrder.reason_type=reason_id;
		mCancelOrderTask=new CancelOrderTask(context, mCancelOrder);
		mCancelOrderTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}
	public class CancelOrderTask extends BaseAsyncTask {

		private CancelOrder mCancelOrder;

		public CancelOrderTask(Activity context, CancelOrder mCancelOrder) {
			super(context);
			this.mCancelOrder = mCancelOrder;
		}

		@Override
		protected Object doInBackground(Object... params) {
			// TODO Auto-generated method stub
			String json = new JsonBuild().setModel(mCancelOrder).getJson();
			return new CancelOrderNet(context, json);
		}

		@Override
		public void onSuccess(int status,Object object) {
			if (object != null) {
				// TODO Auto-generated method stub
				ToastUtil.showToast(context, R.string.cancel_success);
				db_myordering.onUpdate(order_id,Value.ORDER_STATUS_CANCEL);
				db_myorder.onUpdate(order_id,Value.ORDER_STATUS_CANCEL);
				db_cencel.onWrite(order_id, message+et_message.getText().toString());	
				Intent intent = new Intent(context,
						OrderCancelReason.class);
				intent.putExtra(OrderMsg.extra_order_id,order_id);
				startActivityForResult(intent,requestCode);
				
			} else {
				ToastUtil.showToast(context,R.string.text_fail);
			}
		}

		@Override
		public void onFailed(int status, String msg) {
			if(status==-10120){
				try{
					JSONObject jso=new JSONObject(msg);
					ToastUtil.showToast(context, jso.getString("message"));
				}catch(Exception e){}
			}else{
				ToastUtil.showToast(context,
						getResources().getString(R.string.no_network));
			}
		}
	}
	@Override
	protected void onDestroy() {
		if (mCancelOrderTask != null&& mCancelOrderTask.getStatus() != AsyncTask.Status.FINISHED)
			mCancelOrderTask.cancel(true);
		super.onDestroy();
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(this.requestCode==requestCode){
			finish();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
	@Override
	public void finish() {
		setResult(resultCode,new Intent());
		super.finish();
	}
	public class MyAdapter extends BaseAdapter {
		private List<CancelReason> list;
		private Activity main;
		  public  Map<Integer, Boolean> isSelected; 
		public MyAdapter(Activity context,List<CancelReason> list) {
			this.list=list;
		   main=context;
		   init(0);  
		}
		 //初始化    
	    private void init(int id) {   
	        //这儿定义isSelected这个map是记录每个listitem的状态，初始状态全部为false。    
	        isSelected = new HashMap<Integer, Boolean>();    
	        for (int i = 0; i < list.size(); i++) {  
	        	if(id==i){
	        	    isSelected.put(i, false);    	
	        	}
	        	else{
	        	    isSelected.put(i, false);    
	        	}
	        
	        }    
	    } 
	    public void notifyDataSetChanged(int id) {
	    	this.notifyDataSetChanged();
	    	init(id);
	    }
		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
			
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			ViewHolder_Cancel viewholder;
			if(convertView==null){      
			LayoutInflater inflater=LayoutInflater.from(main);
			convertView=(View)inflater.inflate(R.layout.item_cancel_reason,null);        
			viewholder=new ViewHolder_Cancel();
			viewholder.tv_reason=(TextView)convertView.findViewById(R.id.tv_reason);
			viewholder.layout=(RelativeLayout)convertView.findViewById(R.id.layout);
			convertView.setTag(viewholder);	
			}
			else viewholder=(ViewHolder_Cancel)convertView.getTag();
			viewholder.tv_reason.setText(list.get(position).getReason());
			viewholder.layout.setSelected(isSelected.get(position));
			if(isSelected.get(position)){
				viewholder.tv_reason.setTextColor(main.getColor(R.color.red2));
			}else{
				viewholder.tv_reason.setTextColor(main.getColor(R.color.black));
			}
			return convertView;
			
	}
		public class ViewHolder_Cancel{                   
			TextView tv_reason;
			RelativeLayout layout;
		}
	}
	@Override
	public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
		id=position;
		reason_id = list.get(position).getId();
		message=list.get(position).getReason();
		ViewHolder_Cancel vHollder = (ViewHolder_Cancel) v.getTag();
		for (int i = 0; i < list.size(); i++) {
			if (i == position) {
				mMyAdapter.isSelected.put(i, true);
				btn_confirm.setEnabled(true);
			} else {
				mMyAdapter.isSelected.put(i, false);
			}
		}
		mMyAdapter.notifyDataSetInvalidated();
	}
	@Override
	public void onNotifyData(DATA_STATUS data_status, DATA_TYPE data_type, int status,Object object) {
	    switch(data_type){
	        case CANCELREASON:
	        	if (IsDataFail.isDataFail(data_status)) {
	                return;
	            }
	    		String cancel_reason_json = SharedPreUtil.getStringValue(this,
	    				SharedPreEncryptUtil.cancel_reason_json, "");
	    		CancelReasonList mCancelReasonList = (CancelReasonList) new JsonBuild().getData(
	    				CancelReasonList.class, cancel_reason_json);
	    		if(list!=null&&mCancelReasonList!=null){
	    			list.clear();
	    			list.addAll(mCancelReasonList.getList());
	    			if(list!=null&&list.size()>0){
	    				message=list.get(0).getReason();
	    			}
	    			mMyAdapter.notifyDataSetChanged(id);
	    		}
	        	break;
	    }
	}
}
